#!/usr/bin/env ts-node

import { PrismaClient } from '@prisma/client';

async function checkDataCompatibility() {
  console.log('🔍 检查数据库兼容性...');
  
  const prisma = new PrismaClient();
  
  try {
    // 检查现有股票数据
    console.log('\n📊 当前数据库统计:');
    const totalStocks = await prisma.stock.count();
    console.log(`总股票数: ${totalStocks}`);
    
    // 检查市场分布
    const marketStats = await prisma.stock.groupBy({
      by: ['marketId'],
      _count: { _all: true }
    });
    
    const markets = await prisma.market.findMany();
    const marketMap = new Map(markets.map(m => [m.id, m]));
    
    console.log('\n🏢 市场分布:');
    for (const stat of marketStats) {
      const market = marketMap.get(stat.marketId);
      console.log(`${market?.marketName}: ${stat._count._all} 只`);
    }
    
    // 检查板块分布
    const sectorStats = await prisma.stock.groupBy({
      by: ['sector'],
      _count: { _all: true }
    });
    
    console.log('\n🎯 板块分布:');
    for (const stat of sectorStats) {
      const sector = stat.sector || '未分类';
      console.log(`${sector}: ${stat._count._all} 只`);
    }
    
    // 检查有实时数据的股票
    const realtimeCount = await prisma.stockRealtime.count();
    console.log(`\n📈 有实时数据的股票: ${realtimeCount} 只`);
    
    // 检查最近更新时间
    const latestUpdate = await prisma.stockRealtime.findFirst({
      orderBy: { updateTime: 'desc' },
      select: { updateTime: true }
    });
    
    if (latestUpdate) {
      console.log(`📅 最近数据更新时间: ${latestUpdate.updateTime.toLocaleString()}`);
    }
    
    // 检查是否有未分类的股票
    const unclassifiedCount = await prisma.stock.count({
      where: {
        OR: [
          { sector: null },
          { sector: '' }
        ]
      }
    });
    
    console.log(`\n⚠️ 未分类股票数量: ${unclassifiedCount} 只`);
    
    if (unclassifiedCount > 0) {
      console.log('\n💡 建议运行导入脚本更新板块分类信息');
    }
    
  } catch (error) {
    console.error('❌ 检查失败:', error);
  } finally {
    await prisma.$disconnect();
  }
}

checkDataCompatibility().then(() => {
  console.log('\n✅ 兼容性检查完成');
  process.exit(0);
}).catch(console.error);